library("quantmod");
library("tseries");
library("fUnitRoots");


hedge_ratio = function(Name1, Name2) {

	#Name1 = "601398.SS"
	#Name2 = "601988.SS"
	hedgeTrainingStartDate = as.Date("2012-07-29") #Start date for training the hedge ratio
	hedgeTrainingEndDate = as.Date("2013-07-29") #End date for training the hedge ratio
	
	symbolList = c(Name1, Name2);

	symbolData <- new.env() #Make a new environment for quantmod to store data in
	getSymbols(symbolList, env = symbolData, src = "yahoo", from = hedgeTrainingStartDate, to=hedgeTrainingEndDate)
 
	stockPairs <- list(
 		 a = coredata(Cl(eval(parse(text=paste("symbolData$\"",symbolList[1],"\"",sep="")))))   #Stock A
		,b = coredata(Cl(eval(parse(text=paste("symbolData$\"",symbolList[2],"\"",sep=""))))) #Stock B
		,name="stockPair")

	dev.new();
	par(mfrow=c(2,2));
	
	
	plot(stockPairs$a, 
		main=stockPairs$name, 
		ylab="Price", type="l",col="blue",
		ylim=c( (0.99*min(rbind(stockPairs$a,stockPairs$b))),(1.01*max(rbind(stockPairs$a,stockPairs$b))) )
	)
	
	offset = stockPairs$b[1] - stockPairs$a[1]
	
	lines(stockPairs$b-offset)
	dailyRet.a <- na.omit((Delt(stockPairs$a,type="arithmetic")));
	dailyRet.b <- na.omit((Delt(stockPairs$b,type="arithmetic")));

	dailyRet.a <- dailyRet.a[is.finite(dailyRet.a)]; #Strip out any Infs (first ret is Inf)
	dailyRet.b <- dailyRet.b[is.finite(dailyRet.b)];

	print( length(dailyRet.a) )
	print( length(dailyRet.b) )
	
	regression <- lm(dailyRet.a ~ dailyRet.b + 0);
	beta <- coef(regression)[1];
	print(paste("The beta or Hedge Ratio is: ",beta,sep=""))
	plot(x=dailyRet.b,y=dailyRet.a,type="p",main="Regression of RETURNS for Stock A & B") #Plot the daily returns
	lines(x=dailyRet.b,y=(dailyRet.b*beta),col="blue")#Plot in linear line we used in the regression

	spread <- stockPairs$a - beta*stockPairs$b; #Could actually just use the residual form the regression its the same thing
	spreadRet <- Delt(spread,type="arithmetic");
	spreadRet <- na.omit(spreadRet);

	adfResults <- adf.test((spread),k=0,alternative="stationary");
	#spreadRet[!is.na(spreadRet)]
	print(adfResults)

	if(adfResults$p.value <= 0.05){
		print(paste("The spread is likely Cointegrated with a pvalue of ",adfResults$p.value,sep=""))
	} else {
		print(paste("The spread is likely NOT Cointegrated with a pvalue of ",adfResults$p.value,sep=""))
	}

	plot((spreadRet), type="l",main="Spread Returns"); #Plot the cumulative sum of the spread
	plot(spread, type="l",main="Spread Actual"); #Plot the cumulative sum of the spread
}
